import { Injectable } from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router} from '@angular/router';
import { Observable } from 'rxjs';
import {AuthService} from '../services/auth.service';

@Injectable({
  providedIn: 'root'
})
export class AdminGuard implements CanActivate {

constructor(private authservice:AuthService,private router:Router) {
}


  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    //return true;
   return new Promise(((resolve)=>{
     this.authservice.getRole()
       .then((data:any)=>{
         if (data.msg=='ok'){
           if(data.role=='admin'){
             resolve(true);
           }
           else {
             resolve(false);
             this.router.navigate(['/p403']);
           }
         }
         else {
           resolve(false);
           this.router.navigate(['/p403']);
         }
       })

   }))

  }

}
